import logging
import datetime
import os

# 定义日志级别的映射
log_l = {
    "info": logging.INFO,
    "debug": logging.DEBUG,
    "warning": logging.WARNING,
    "error": logging.ERROR
}


# 1. 创建类
class Logger:
    # 2. 定义参数: 写入日志文件的名称test.log, logger名称, 日志级别总开关
    def __init__(self, log_file, log_name, log_level):
        self.logger = logging.getLogger(log_name)  # 设置logger名称
        self.logger.setLevel(log_l[log_level])  # 通过映射关系设置日志级别

        # 3. 编写控制台handler
        if not self.logger.handlers:  # 判断当前是否有handler,如果没有才创建handler
            fh_stream = logging.StreamHandler()
            fh_stream.setLevel(log_l[log_level])
            formatter = logging.Formatter('%(asctime)s - %(name)s -%(lineno)s - %(levelname)s - %(message)s')
            fh_stream.setFormatter(formatter)
            self.logger.addHandler(fh_stream)
        # 4. 编写输出日志文件handler
            fh_file = logging.FileHandler(log_file)
            fh_file.setLevel(log_l[log_level])
            fh_file.setFormatter(formatter)
            self.logger.addHandler(fh_file)


# 设置logs目录
log_path = os.path.dirname(__file__)  # 获取当前路径
log_path = log_path + os.path.sep + "logs"  # 拼接logs路径
current_data = datetime.datetime.now().strftime("%Y-%m-%d")  # 其获取当前时间
log_file = os.path.join(log_path, current_data + ".log")  # 拼接为完整路径
# print(log_file)

# 定义日志级别
loglevel = "info"


# 初始化log工具类, 提供给其他类使用
def my_log(log_name=__file__):
    if not os.path.exists(log_path):
        os.mkdir(log_path)
    return Logger(log_file, log_name, loglevel).logger


if __name__ == '__main__':
    log = my_log("实例化工具类时定义名称")
    log.info("这是一个info信息")